<template>
  <div class="smartlock-page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>智能门锁管理</h2>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          @click="refreshData" 
          :loading="loading"
          icon="el-icon-refresh"
          size="medium"
        >
          刷新数据
        </el-button>
       
      </div>
    </div>


    <!-- 搜索和筛选栏 -->
    <el-form :inline="true" @submit.native.prevent class="search-form">
      <el-form-item>
        <el-input
          v-model="searchKeyword"
          @keyup.native.enter="handleSearch"
          @input="handleSearch"
          placeholder="搜索设备名称、学院、教室或IP地址"
          style="width: 280px; margin-right: 15px"
          clearable
        >
          <i slot="prefix" class="el-icon-search"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select 
          v-model="filters.status" 
          @change="handleFilter"
          placeholder="设备状态"
          style="width: 120px; margin-right: 15px"
          clearable
        >
          <el-option label="全部状态" value=""></el-option>
          <el-option label="已开锁" value="1"></el-option>
          <el-option label="已锁定" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select 
          v-model="filters.college" 
          @change="handleFilter"
          placeholder="学院筛选"
          style="width: 150px; margin-right: 15px"
          clearable
        >
          <el-option label="全部学院" value=""></el-option>
          <el-option 
            v-for="college in collegeList" 
            :key="college" 
            :label="college" 
            :value="college"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button 
          @click="resetFilters"
          icon="el-icon-refresh"
        >
          重置
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="success" 
          @click="searchDevices" 
          :loading="searching"
          icon="el-icon-search"
        >
          搜索并添加设备
        </el-button>
      </el-form-item>
        <el-form-item>
        <el-button 
          type="primary" 
          @click="handleAddition" 
          icon="el-icon-circle-plus-outline"
        >
          新增
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="info" 
          @click="syncDeviceStatus" 
          :loading="syncing"
          icon="el-icon-refresh"
        >
          同步状态
        </el-button>
      </el-form-item>
      <!-- 批量操作区域 -->
      <el-form-item v-if="selectedLocks.length > 0">
        <span class="selected-count">已选择 {{ selectedLocks.length }} 个设备</span>
      </el-form-item>
      <el-form-item v-if="selectedLocks.length > 0">
        <el-button 
          type="success" 
          @click="batchUnlock"
          :loading="batchUnlocking"
          icon="el-icon-unlock"
          size="small"
        >
          批量开锁
        </el-button>
      </el-form-item>
      <el-form-item v-if="selectedLocks.length > 0">
        <el-button 
          type="warning" 
          @click="batchLock"
          :loading="batchLocking"
          icon="el-icon-lock"
          size="small"
        >
          批量关锁
        </el-button>
      </el-form-item>
      <el-form-item v-if="selectedLocks.length > 0">
        <el-button 
          type="primary" 
          @click="batchSetWeeklyTimer"
          icon="el-icon-time"
          size="small"
        >
          批量定时开锁
        </el-button>
      </el-form-item>
    </el-form>



    <!-- 加载状态 -->
    <el-empty 
      v-if="loading" 
      description="正在加载设备数据..."
      style="padding: 4rem 2rem; background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);"
    >
      <i class="el-icon-loading" style="font-size: 36px;"></i>
    </el-empty>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <div class="error-icon">
        <i class="fas fa-exclamation-triangle"></i>
      </div>
      <h3>加载失败</h3>
      <p>{{ error }}</p>
      <el-button 
        type="primary" 
        @click="loadLocks"
        icon="el-icon-refresh"
      >
        重试
      </el-button>
    </div>

    <!-- 门锁设备表格 -->
    <el-table
      v-else-if="paginatedLocks.length > 0"
      :data="paginatedLocks"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="60" align="center">
      </el-table-column>
      
      <el-table-column label="选择" width="60" align="center">
        <template slot="header">
          <el-checkbox 
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          ></el-checkbox>
        </template>
        <template slot-scope="scope">
          <el-checkbox 
            :value="selectedLocks.includes(scope.row.lockId)"
            @input="toggleLockSelection(scope.row.lockId, $event)"
          ></el-checkbox>
        </template>
      </el-table-column>
      
     
      
      <el-table-column prop="college" label="学院" align="center" width="120">
      </el-table-column>
      
      <el-table-column prop="classroom" label="教室" align="center" width="120">
      </el-table-column>
      
      <el-table-column prop="ipAddress" label="IP地址" align="center" width="120">
      </el-table-column>
      
      <el-table-column prop="snCode" label="SN序列号" align="center" width="140" show-overflow-tooltip>
      </el-table-column>
      
      <el-table-column prop="status" label="设备状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.statusClass === 'unlocked' ? 'success' : 'warning'"
            size="small"
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="remarks" label="通道号" align="center" show-overflow-tooltip>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="400">
        <template slot-scope="scope">
          <div class="action-buttons">
            <el-button
              :type="scope.row.switchStatus === 1 ? 'warning' : 'primary'"
              @click="toggleLockStatus(scope.row)"
              :loading="scope.row.operating"
              :icon="scope.row.switchStatus === 1 ? 'el-icon-lock' : 'el-icon-unlock'"
              size="mini"
            >
              {{ scope.row.switchStatus === 1 ? '关锁' : '开锁' }}
            </el-button>
            <el-button
              type="info"
              @click="viewLockDetails(scope.row)"
              icon="el-icon-view"
              size="mini"
            >
              详情
            </el-button>
            <el-button
              type="success"
              @click="editLock(scope.row)"
              icon="el-icon-edit"
              size="mini"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              @click="setWeeklyTimer(scope.row)"
              icon="el-icon-time"
              size="mini"
            >
              定时
            </el-button>
            <el-button
              type="danger"
              @click="deleteLock(scope.row)"
              icon="el-icon-delete"
              size="mini"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div v-if="filteredLocks.length > 0" class="pagination-wrapper">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredLocks.length"
        background
      >
      </el-pagination>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!loading && filteredLocks.length === 0" class="empty-state">
      <el-empty 
        :description="searchKeyword || filters.status || filters.college ? '没有找到符合条件的设备' : '还没有智能门锁设备，请先搜索并添加设备'"
      >
        <el-button 
          v-if="!searchKeyword && !filters.status && !filters.college"
          slot="bottom"
          type="primary" 
          @click="searchDevices" 
          :loading="searching"
          icon="el-icon-search"
        >
          搜索并添加设备
        </el-button>
        <el-button 
          v-else
          slot="bottom"
          @click="resetFilters"
          icon="el-icon-refresh"
        >
          清除筛选条件
        </el-button>
      </el-empty>
    </div>
    
    <!-- 门锁详情模态框 -->
    <el-dialog
      title="门锁设备详情"
      :visible.sync="showDetailsModal"
      width="600px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
      custom-class="smart-lock-modal"
    >
      <div v-if="detailsLock" class="lock-details-content">
        <el-card class="details-card" shadow="never">
          <div class="details-grid">
            <div class="detail-item">
              <label class="detail-label">设备ID：</label>
              <span class="detail-value">{{ detailsLock.lockId || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">设备名称：</label>
              <span class="detail-value">{{ detailsLock.name || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">学院：</label>
              <span class="detail-value">{{ detailsLock.college || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">教室：</label>
              <span class="detail-value">{{ detailsLock.classroom || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">IP地址：</label>
              <span class="detail-value">{{ detailsLock.ipAddress || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">端口号：</label>
              <span class="detail-value">{{ detailsLock.portNumber || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">SN序列号：</label>
              <span class="detail-value">{{ detailsLock.snCode || '无' }}</span>
            </div>
            <div class="detail-item">
              <label class="detail-label">当前状态：</label>
              <span class="detail-value">
            <el-tag :type="detailsLock.statusClass === 'unlocked' ? 'success' : 'warning'">
              {{ detailsLock.status }}
            </el-tag>
              </span>
            </div>
            <div class="detail-item detail-item-full">
              <label class="detail-label">通道号：</label>
              <span class="detail-value">{{ detailsLock.remarks || '无' }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 实时状态刷新 -->
        <div class="details-actions" style="margin-top: 20px; text-align: center;">
          <el-button 
            @click="refreshLockDetails" 
            :loading="refreshingDetails"
            icon="el-icon-refresh"
            type="primary"
          >
            刷新状态
          </el-button>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetailsModal">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 门锁编辑模态框 -->
    <el-dialog
      title="编辑门锁信息"
      :visible.sync="showEditModal"
      width="500px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
      custom-class="smart-lock-modal"
    >
      <el-form ref="editForm" :model="editingLock" label-width="80px">
        <el-form-item label="学院" prop="college">
          <el-input 
            v-model="editingLock.college" 
            placeholder="请输入学院名称"
          />
        </el-form-item>
        
        <el-form-item label="教室" prop="classroom">
          <el-input 
            v-model="editingLock.classroom" 
            placeholder="请输入教室名称"
          />
        </el-form-item>
        
        <el-form-item label="IP地址">
          <el-input 
            v-model="editingLock.ipAddress" 
            placeholder="192.168.1.100"
            readonly
          />
        </el-form-item>
        
        <el-form-item label="端口号">
          <el-input 
            v-model="editingLock.portNumber" 
            placeholder="8080"
            readonly
          />
        </el-form-item>
        
        <el-form-item label="SN码">
          <el-input 
            v-model="editingLock.snCode" 
            placeholder="设备序列号"
            readonly
          />
        </el-form-item>
        
        <el-form-item label="通道号">
          <el-input 
            v-model="editingLock.remarks" 
            placeholder="请输入通道号信息"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeEditModal">取消</el-button>
        <el-button 
          type="primary" 
          @click="saveLockInfo" 
          :loading="saving"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
    
    <!-- 每周定时开锁模态框 -->
    <el-dialog
      :title="isBatchTimerMode ? '批量设置每周定时开锁' : '设置每周定时开锁'"
      :visible.sync="showScheduleModal"
      width="600px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
      custom-class="smart-lock-modal weekly-timer-modal"
    >
      <div class="schedule-content">
        <!-- 设备信息显示 -->
        <div class="device-info-section">
          <el-alert
            :title="isBatchTimerMode ? `批量设置定时开锁 (${selectedLocks.length}个设备)` : '设置每周定时开锁'"
            :type="isBatchTimerMode ? 'warning' : 'success'"
            :description="isBatchTimerMode ? 
              `将为选中的 ${selectedLocks.length} 个设备设置相同的每周定时开锁任务` :
              '为该设备设置每周定时开锁，系统将在指定时间自动执行开锁操作'"
            :closable="false"
            show-icon
            style="margin-bottom: 20px;"
          >
          </el-alert>
          
          <!-- 设备信息显示 -->
          <div v-if="isBatchTimerMode" class="batch-device-preview">
            <div class="device-list-header">
              <span class="device-count">选中设备 ({{ selectedLocks.length }}个)：</span>
            </div>
            <div class="device-list-content">
              <el-tag 
                v-for="lockId in selectedLocks.slice(0, 8)" 
                :key="lockId"
                size="small" 
                style="margin: 2px 4px;"
              >
                {{ getLockNameById(lockId) }}
              </el-tag>
              <span v-if="selectedLocks.length > 8" class="more-devices">
                等{{ selectedLocks.length }}个设备
              </span>
            </div>
          </div>
          <div v-else-if="selectedLockForTimer" class="single-device-info">
            <span class="device-name">设备：{{ selectedLockForTimer.name }}</span>
          </div>
        </div>
        
        <!-- 批量设置进度显示 -->
        <div v-if="scheduleSaving && isBatchTimerMode" class="batch-progress-section">
          <div class="progress-header">
            <span>正在设置定时任务...</span>
            <span class="progress-text">{{ batchTimerProgress.current }}/{{ batchTimerProgress.total }}</span>
          </div>
          <el-progress 
            :percentage="Math.round((batchTimerProgress.current / batchTimerProgress.total) * 100)"
            :show-text="false"
            style="margin: 10px 0;"
          ></el-progress>
          <div class="progress-details">
            <span class="success-count">成功: {{ batchTimerProgress.success }}</span>
            <span class="failed-count">失败: {{ batchTimerProgress.failed }}</span>
          </div>
        </div>
        
        <!-- 定时设置表单 -->
        <div class="timer-form-section">
          <el-form ref="scheduleForm" :model="timerFormData" :rules="weeklyTimerRules" label-width="80px">
            <el-form-item label="开锁时间" prop="scheduleHour">
              <div class="time-input-group">
                <el-input-number
                  v-model="timerFormData.scheduleHour"
                  :min="0"
                  :max="23"
                  controls-position="right"
                  style="width: 100px;"
                ></el-input-number>
                <span class="time-separator">时</span>
                <el-input-number
                  v-model="timerFormData.scheduleMinute"
                  :min="0"
                  :max="59"
                  controls-position="right"
                  style="width: 100px;"
                ></el-input-number>
                <span class="time-separator">分</span>
              </div>
            </el-form-item>
            
            <el-form-item label="重复周期" prop="scheduleDaysOfWeek">
              <div class="days-selection-container">
                <el-checkbox-group v-model="timerFormData.scheduleDaysOfWeek" class="days-checkbox-group">
                  <el-checkbox :label="0" class="day-checkbox">周一</el-checkbox>
                  <el-checkbox :label="1" class="day-checkbox">周二</el-checkbox>
                  <el-checkbox :label="2" class="day-checkbox">周三</el-checkbox>
                  <el-checkbox :label="3" class="day-checkbox">周四</el-checkbox>
                  <el-checkbox :label="4" class="day-checkbox">周五</el-checkbox>
                  <el-checkbox :label="5" class="day-checkbox">周六</el-checkbox>
                  <el-checkbox :label="6" class="day-checkbox">周日</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
            
            <el-form-item>
              <div class="quick-select-buttons">
                <el-button @click="selectWorkdays" size="small" type="text">工作日</el-button>
                <el-button @click="selectWeekends" size="small" type="text">周末</el-button>
                <el-button @click="selectAllDays" size="small" type="text">每天</el-button>
                <el-button @click="clearDays" size="small" type="text">清除</el-button>
              </div>
            </el-form-item>
            
            <el-form-item label="循环次数" prop="loopCount">
              <div class="loop-count-input-group">
                <el-input-number
                  v-model="timerFormData.loopCount"
                  :min="0"
                  :max="99999"
                  controls-position="right"
                  style="width: 120px;"
                ></el-input-number>
                <span class="loop-count-unit">次</span>
                <span class="loop-count-help">(-2表示无限循环，0代表只执行一次)</span>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelWeeklyTimer" :disabled="scheduleSaving">取消</el-button>
        <el-button 
          type="primary" 
          @click="createWeeklyTimer"
          :loading="scheduleSaving"
        >
          {{ isBatchTimerMode ? '批量设置' : '确定设置' }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 新增模态框 -->
    <el-dialog
      :title="messageBoxTitle"
      :visible.sync="messageBox"
      width="520px"
      :close-on-click-modal="false"
      :append-to-body="true"
      :modal="true"
      :modal-append-to-body="true"
      :lock-scroll="true"
      custom-class="smart-lock-modal"
    >
      <el-form ref="newLockFormRef" :model="newLockForm" :rules="newLockRules" label-width="100px">
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="newLockForm.ipAddress" placeholder="例如 192.168.1.100"></el-input>
        </el-form-item>
        <el-form-item label="SN序列号" prop="snCode">
          <el-input v-model="newLockForm.snCode" placeholder="设备SN码"></el-input>
        </el-form-item>
        <el-form-item label="通信端口" prop="portNumber">
          <el-input-number v-model="newLockForm.portNumber" :min="0" :max="65535" controls-position="right" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item label="开关状态" prop="switch_status">
          <el-radio-group v-model="newLockForm.switch_status" disabled>
            <el-radio :label="1">开</el-radio>
            <el-radio :label="0">关</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-select v-model="newLockForm.college" placeholder="请选择学院" clearable style="width: 250px">
            <el-option v-for="i in collegeList" :key="i" :label="i" :value="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室" prop="classroom">
          <el-input v-model="newLockForm.classroom" placeholder="请输入教室"></el-input>
        </el-form-item>
        <el-form-item label="通道号" prop="remarks">
          <el-input v-model="newLockForm.remarks" type="textarea" :rows="3" placeholder="可填写通道号等信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelNewLock">取消</el-button>
        <el-button type="primary" @click="saveNewLock" :loading="creating">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 接口路径常量定义
const SMARTLOCK_API = {
  LOCK_SELECT_ALL: '/api/smart/lock/selectAll',
  LOCK_GET_BY_ID: '/api/smart/lock/getById',
  LOCK_SEARCH_CHECK: '/api/smart/lock/searchcheck',
  LOCK_INSERT: '/api/smart/lock/insertLock',
  LOCK_UPDATE: '/api/smart/lock/updateLock',
  LOCK_UPDATE_STATUS: '/api/smart/lock/updateSwitchStatus',
  LOCK_DELETE: '/api/smart/lock/deleteLock',
  LOCK_COUNT_STATS: '/api/smart/lock/countNum',
  // 添加用户信息接口
  USER_INFO: '/api/user/current',
  // 查询设备状态接口
  LOCK_QUERY_STATUS: '/api/smart/lock/queryStatus',
  // 定时开锁相关接口 - 对应SmartLockController真实接口  
  ADD_TIMER: '/api/smart/lock/addTimer',
  GET_TIMER_LIST: '/api/smart/lock/getTimer',
  GET_TIMER_BY_ID: '/api/smart/lock/getTimerById',
  CANCEL_WEEKLY_TIMER: '/api/smart/lock/cancelWeeklyTimer',
  UPDATE_TIMER_STATUS: '/api/smart/lock/updateTimerStatus'
};

export default {
  name: 'smartlockpage',
  
  data() {
    return {
      // 数据状态
      locks: [],
      loading: false,
      error: null,
      collegeList:[],
      
      // 操作状态
      searching: false,
      saving: false,
      batchUnlocking: false,
      batchLocking: false,
      syncing: false,
      
      // 搜索和筛选
      searchKeyword: '',
      filters: {
        status: '',
        college: ''
      },
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      
      // 编辑模态框
      showEditModal: false,
      editingLock: {},
      
      // 详情模态框
      showDetailsModal: false,
      detailsLock: null,
      refreshingDetails: false,
      
      // 批量选择
      selectedLocks: [],
      
      // 定时开锁模态框
      showScheduleModal: false,
      scheduleSaving: false,
      selectedLockForTimer: null, // 当前选择的锁（单个设置）
      isBatchTimerMode: false, // 是否为批量定时模式
      batchTimerProgress: { // 批量设置进度
        current: 0,
        total: 0,
        success: 0,
        failed: 0
      },
      // 定时器表单数据
      timerFormData: {
        scheduleHour: 9, // 开锁小时
        scheduleMinute: 0, // 开锁分钟
        scheduleDaysOfWeek: [], // 每周的天数: [1,2,3,4,5,6,7] 对应周一到周日
        loopCount: 0 // 循环次数，默认0表示不限制次数
      },
      
      // 统计数据
      stats: {
        totalLocks: 0,
        unlockedCount: 0,
        lockedCount: 0,
        onlineCount: 0
      },
      
      // 用户信息
      userInfo: null,
      
      // 自动刷新
      autoRefresh: false,
      refreshTimer: null,

      // 新增框
      messageBox:false,
      messageBoxTitle:'新增'
      ,
      newLockForm: {
        ipAddress: '',
        snCode: '',
        portNumber: null,
        switch_status: 0,
        college: '',
        classroom: '',
        remarks: ''
      },
      newLockRules: {
        ipAddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' },{pattern:/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/,message:'请输入正确的IP地址',trigger:'blur'}],
        snCode: [{ required: true, message: '请输入SN序列号', trigger: 'blur' }],
        portNumber: [{ required: true, message: '请输入端口号', trigger: 'change' }],
        switch_status: [{ required: true, message: '请选择开关状态', trigger: 'change' }],
        college: [{ required: true, message: '请选择学院或填写', trigger: 'blur' }],
        classroom: [{ required: true, message: '请输入教室', trigger: 'blur' }]
      },
      creating: false
    }
  },
  
  computed: {
    // 学院列表（用于筛选）
    collegeList() {
      const colleges = [...new Set(this.locks.map(lock => lock.college).filter(college => college && college !== '-'))];
      return colleges.sort();
    },
    
    // 搜索和筛选后的门锁列表
    filteredLocks() {
      let filtered = [...this.locks];
      
      // 关键词搜索
      if (this.searchKeyword && this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase().trim();
        filtered = filtered.filter(lock => {
          return (
            lock.name.toLowerCase().includes(keyword) ||
            (lock.college && lock.college.toLowerCase().includes(keyword)) ||
            (lock.classroom && lock.classroom.toLowerCase().includes(keyword)) ||
            (lock.ipAddress && lock.ipAddress.toLowerCase().includes(keyword)) ||
            (lock.snCode && lock.snCode.toLowerCase().includes(keyword))
          );
        });
      }
      
      // 状态筛选
      if (this.filters.status !== '' && this.filters.status !== null) {
        const statusValue = parseInt(this.filters.status);
        filtered = filtered.filter(lock => lock.switchStatus === statusValue);
      }
      
      // 学院筛选
      if (this.filters.college && this.filters.college.trim()) {
        filtered = filtered.filter(lock => lock.college === this.filters.college);
      }
      
      return filtered;
    },
    
    // 分页后的门锁列表
    paginatedLocks() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredLocks.slice(start, end);
    },
    
    // 检查用户是否可以编辑锁信息（允许所有用户编辑）
    canEditLocks() {
      return true; // 移除权限限制，所有用户都可以编辑
    },
    
    // 全选相关计算属性
    checkAll: {
      get() {
        // 全选应该基于所有数据，不只是筛选结果
        return this.locks.length > 0 && 
               this.selectedLocks.length === this.locks.length;
      },
      set(val) {
        // 这个setter会被handleCheckAllChange处理
      }
    },
    
    isIndeterminate() {
      const selectedCount = this.selectedLocks.length;
      // 中间状态：有选择但不是全选
      return selectedCount > 0 && selectedCount < this.locks.length;
    },
    
    getSelectAllText() {
      if (this.checkAll) {
        return '取消全选';
      } else if (this.isIndeterminate) {
        return '全选';
      } else {
        return '全选';
      }
    },
    
    // 定时器相关计算属性
    
    weeklyTimerRules() {
      return {
        scheduleHour: [
          { validator: this.validateTime, trigger: 'change' }
        ],
        scheduleDaysOfWeek: [
          { validator: this.validateDaysOfWeek, trigger: 'change' }
        ],
        loopCount: [
          { validator: this.validateLoopCount, trigger: 'change' }
        ]
      };
    },
  },
  
  async mounted() {
    // 先检查登录状态和token
    this.checkAuth();
    await this.loadUserInfo();
    this.loadLocks();
    // 暂时不在初始化时加载定时任务列表，等用户主动打开时再加载
    // this.loadScheduleList();
  },
  
  methods: {
    // 检查认证状态
    checkAuth() {
      const Cookie = require('js-cookie');
      const token = Cookie.get('token');
      if (!token || token.trim() === '') {
        this.$message.error('请先登录');
        this.$router.push('/login');
        return false;
      }
      return true;
    },
    
    // 加载用户信息
    async loadUserInfo() {
      if (!this.checkAuth()) return;
      
      try {
        console.log('开始从API获取用户信息...');
        const response = await this.$get(SMARTLOCK_API.USER_INFO);
        
        if (response && response.code === 200 && response.data) {
          this.userInfo = response.data;
          // 保存用户信息到localStorage
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
          console.log('从API加载用户信息:', this.userInfo);
        } else {
          // 尝试从localStorage获取
          const storedUserInfo = localStorage.getItem('userInfo');
          if (storedUserInfo) {
            this.userInfo = JSON.parse(storedUserInfo);
            console.log('从localStorage加载用户信息:', this.userInfo);
          } else {
            console.warn('未找到用户信息，使用默认权限');
            this.userInfo = { permissionLevel: 0 };
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 尝试从localStorage获取
        const storedUserInfo = localStorage.getItem('userInfo');
        if (storedUserInfo) {
          this.userInfo = JSON.parse(storedUserInfo);
        } else {
          this.userInfo = { permissionLevel: 0 };
        }
        
        // 检查是否是401未授权错误
        if (error.message.includes('401')) {
          this.$message.error('登录已过期，请重新登录');
          const Cookie = require('js-cookie');
          Cookie.remove('token');
          localStorage.removeItem('userInfo');
          this.$router.push('/login');
        }
      }
    },
    //删除数据
    deleteLock(lock) {
      this.$confirm('确定要删除该门锁吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.$post(SMARTLOCK_API.LOCK_DELETE, { lockId: lock.lockId }).then(res => {
          if (res && res.code === 200) {
            this.$message.success('删除成功');
            this.loadLocks();
          } else {
            this.$message.error('删除失败');
          }
        }).catch(err => {
          console.error('删除失败:', err);
          this.$message.error('删除失败：网络连接异常');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 加载门锁数据
    loadLocks() {
      if (!this.checkAuth()) return;
      
      this.loading = true;
      this.error = null;
      
      // 同时获取锁列表和统计数据
      Promise.all([
        this.$get(SMARTLOCK_API.LOCK_SELECT_ALL),
        this.$get(SMARTLOCK_API.LOCK_COUNT_STATS)
      ]).then(([locksRes, statsRes]) => {
        // 处理锁列表数据
        if (locksRes && locksRes.code === 200) {
          let locks = locksRes.data || [];
          
          // 格式化门锁数据
          this.locks = locks.map(lock => {
            const formatted = this.formatLockInfo(lock);
            return {
              ...formatted,
              operating: false // 添加操作状态标识
            };
          });
          
          console.log('门锁数据加载完成:', this.locks);
          
          if (this.locks.length > 0) {
            this.$message.success('成功加载 ' + this.locks.length + ' 个智能锁设备');
          }
        } else if (locksRes && locksRes.msg) {
          this.error = '获取智能锁设备信息失败：' + locksRes.msg;
          this.$message.error(this.error);
        } else {
          this.error = '获取智能锁设备信息失败：网络错误或后端服务未启动';
          this.$message.error(this.error);
        }
        
        // 处理统计数据
        if (statsRes && statsRes.code === 200) {
          this.stats.totalLocks = statsRes.data || 0;
          // 更新其他统计数据
          this.updateStats();
        } else {
          // 如果统计接口失败，使用本地计算
          this.updateStats();
        }
      }).catch(err => {
        console.error('API请求失败:', err);
        this.error = '获取智能锁设备信息失败：网络连接异常';
        this.$message.error(this.error);
        
        // 处理401未授权错误
        if (err.message && err.message.includes('401')) {
          const Cookie = require('js-cookie');
          Cookie.remove('token');
          localStorage.removeItem('userInfo');
          this.$router.push('/login');
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 格式化锁信息
    formatLockInfo(lock) {
      return {
        lockId: lock.lockId || '',
        college: lock.college || '-',
        classroom: lock.classroom || '-',
        ipAddress: lock.ipAddress || '-',
        portNumber: lock.portNumber || '-',
        snCode: lock.snCode || '-',
        switchStatus: lock.switchStatus !== undefined ? lock.switchStatus : 0,
        remarks: lock.remarks || '-',
        onlineStatus: lock.onlineStatus !== undefined ? lock.onlineStatus : 0,
        // 计算显示属性
        name: lock.college && lock.classroom ? `${lock.college}-${lock.classroom}` : `设备${lock.lockId || ''}`,
        status: lock.switchStatus === 1 ? '已开锁' : '已关锁',
        statusClass: lock.switchStatus === 1 ? 'unlocked' : 'locked',
        statusIcon: lock.switchStatus === 1 ? 'fas fa-unlock' : 'fas fa-lock'
      };
    },
    
    // 更新统计数据
    updateStats() {
      this.stats.totalLocks = this.locks.length;
      this.stats.unlockedCount = this.locks.filter(lock => lock.switchStatus === 1).length;
      this.stats.lockedCount = this.locks.filter(lock => lock.switchStatus === 0).length;
      this.stats.onlineCount = this.locks.filter(lock => lock.ipAddress !== '-').length;
    },
    
    // 处理搜索
    handleSearch() {
      // 搜索时重置到第一页
      this.currentPage = 1;
      // 搜索通过计算属性自动处理
      console.log('搜索关键词:', this.searchKeyword);
    },
    
    // 处理筛选
    handleFilter() {
      // 筛选时重置到第一页
      this.currentPage = 1;
      console.log('筛选条件:', this.filters);
    },
    
    // 重置筛选条件
    resetFilters() {
      this.searchKeyword = '';
      this.filters.status = '';
      this.filters.college = '';
      this.currentPage = 1;
      this.$message.info('已重置搜索和筛选条件');
    },
    
    // 分页处理
    handleCurrentChange(page) {
      this.currentPage = page;
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1; // 改变页面大小时重置到第一页
    },
    
    // 批量选择相关方法
    toggleLockSelection(lockId, checked) {
      if (checked) {
        if (!this.selectedLocks.includes(lockId)) {
          this.selectedLocks.push(lockId);
        }
      } else {
        const index = this.selectedLocks.indexOf(lockId);
        if (index > -1) {
          this.selectedLocks.splice(index, 1);
        }
      }
    },
    
    clearSelection() {
      this.selectedLocks = [];
      // 强制更新视图以确保状态同步
      this.$nextTick(() => {
        this.$forceUpdate();
      });
      this.$message.info('已清空选择');
    },
    
    // 全选/取消全选处理
    handleCheckAllChange(val) {
      if (val) {
        // 全选：选择所有设备（不只是筛选结果）
        this.selectedLocks = this.locks.map(lock => lock.lockId);
        this.$message.success(`已全选所有 ${this.selectedLocks.length} 个设备`);
      } else {
        // 取消全选
        this.selectedLocks = [];
        this.$message.info('已取消全选');
      }
    },
    
    // 批量开锁
    batchUnlock() {
      this.executeBatchOperation(1, '开锁');
    },
    
    // 批量关锁
    batchLock() {
      this.executeBatchOperation(0, '关锁');
    },
    
    // 通用批量操作方法  
    executeBatchOperation(targetStatus, actionText) {
      if (this.selectedLocks.length === 0) {
        this.$message.warning(`请先选择要${actionText}的设备`);
        return;
      }
      
      // 过滤出已选择的锁设备
      const selectedLockObjects = this.locks.filter(lock => 
        this.selectedLocks.includes(lock.lockId)
      );
      
      // 检查是否有设备已经是目标状态
      const alreadyInTargetStatus = selectedLockObjects.filter(lock => lock.switchStatus === targetStatus);
      if (alreadyInTargetStatus.length > 0) {
        const statusText = targetStatus === 1 ? '开锁' : '关锁';
        this.$message.warning(`有 ${alreadyInTargetStatus.length} 个设备已经是${statusText}状态，将跳过这些设备`);
      }
      
      // 过滤出需要操作的设备
      const locksToOperate = selectedLockObjects.filter(lock => lock.switchStatus !== targetStatus);
      
      if (locksToOperate.length === 0) {
        const statusText = targetStatus === 1 ? '开锁' : '关锁';
        this.$message.info(`所选设备都已经是${statusText}状态`);
        return;
      }
      
      // 弹出确认对话框
      this.$confirm(
        `确定要批量${actionText} ${locksToOperate.length} 个门锁吗？`, 
        `批量${actionText}确认`, 
        {
          confirmButtonText: `确定${actionText}`,
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      ).then(() => {
        this.executeBatchOperationAction(locksToOperate, targetStatus, actionText);
      }).catch(() => {
        this.$message.info(`已取消批量${actionText}操作`);
      });
    },
    
    // 执行批量操作
    executeBatchOperationAction(locks, targetStatus, actionText) {
      // 设置对应的loading状态
      if (targetStatus === 1) {
        this.batchUnlocking = true;
      } else {
        this.batchLocking = true;
      }
      
      let successCount = 0;
      let failCount = 0;
      let completedCount = 0;
      const totalCount = locks.length;
      
      this.$message.info(`开始批量${actionText}，共 ${totalCount} 个设备...`);
      
      // 并发执行所有操作
      locks.forEach(lock => {
        // 设置单个锁的操作状态
        lock.operating = true;
        
        this.$post(SMARTLOCK_API.LOCK_UPDATE_STATUS, {
          lockId: lock.lockId,
          switchStatus: targetStatus
        })
        .then(res => {
          if (res && res.code === 200) {
            successCount++;
            // 更新本地状态
            lock.switchStatus = targetStatus;
            lock.status = targetStatus === 1 ? '已开锁' : '已关锁';
            lock.statusClass = targetStatus === 1 ? 'unlocked' : 'locked';
            lock.statusIcon = targetStatus === 1 ? 'fas fa-unlock' : 'fas fa-lock';
          } else {
            failCount++;
            console.error(`${actionText}失败:`, lock.name, res.msg);
          }
        })
        .catch(error => {
          failCount++;
          console.error(`${actionText}失败:`, lock.name, error);
        })
        .finally(() => {
          lock.operating = false;
          completedCount++;
          
          // 所有操作完成后显示结果
          if (completedCount === totalCount) {
            // 重置loading状态
            this.batchUnlocking = false;
            this.batchLocking = false;
            
            if (successCount > 0) {
              this.$message.success(`批量${actionText}完成！成功 ${successCount} 个，失败 ${failCount} 个`);
              // 更新统计数据
              this.updateStats();
            } else {
              this.$message.error(`批量${actionText}失败，请检查网络连接或设备状态`);
            }
            
            // 清空选择
            this.clearSelection();
          }
        });
      });
    },
    
    // 搜索网络设备并自动添加
    searchDevices() {
      if (!this.checkAuth()) return;
      
      this.searching = true;
      this.$message.info('开始搜索网络中的设备...');
      
      // 第一步：搜索网络设备（注意：这个接口返回void，不需要检查返回值）
      this.$get(SMARTLOCK_API.LOCK_SEARCH_CHECK)
        .then(() => {
          // searchcheck接口成功执行（即使返回void）
          this.$message.success('设备搜索完成，正在添加新设备...');
          
          // 等待一小段时间确保搜索完成，然后执行插入操作
          return new Promise(resolve => {
            setTimeout(() => {
              resolve(this.$post(SMARTLOCK_API.LOCK_INSERT));
            }, 1000);
          });
        })
        .then(insertResponse => {
          if (insertResponse && insertResponse.code === 200) {
            this.$message.success('设备搜索和添加完成！发现并添加了新设备');
            // 重新加载设备列表和统计数据
            this.loadLocks();
          } else if (insertResponse && insertResponse.msg) {
            // 即使是"添加失败"也可能是因为没有新设备
            if (insertResponse.msg.includes('添加失败')) {
              this.$message.info('搜索完成，没有发现新设备');
            } else {
              this.$message.warning('设备添加遇到问题：' + insertResponse.msg);
            }
            // 无论如何都重新加载数据
            this.loadLocks();
          } else {
            throw new Error('添加设备时服务器响应异常');
          }
        })
        .catch(error => {
          console.error('搜索或添加设备失败:', error);
          
          // 区分不同类型的错误
          if (error.response && error.response.status === 401) {
            this.$message.error('登录已过期，请重新登录');
            const Cookie = require('js-cookie');
            Cookie.remove('token');
            localStorage.removeItem('userInfo');
            this.$router.push('/login');
          } else if (error.response && error.response.status >= 500) {
            this.$message.error('服务器错误，请稍后重试');
          } else if (error.message && error.message.includes('timeout')) {
            this.$message.error('请求超时，网络连接不稳定');
          } else {
            this.$message.error('操作失败: ' + (error.message || '未知错误'));
          }
        })
        .finally(() => {
          this.searching = false;
        });
    },
    
    // 开锁/关锁切换
    toggleLockStatus(lock) {
      if (!this.checkAuth()) return;
      if (lock.operating) return;
      
      const targetStatus = lock.switchStatus === 1 ? 0 : 1; // 切换状态
      const actionText = targetStatus === 1 ? '开锁' : '关锁';
      
      lock.operating = true;
      
      this.$post(SMARTLOCK_API.LOCK_UPDATE_STATUS, {
        lockId: lock.lockId,
        switchStatus: targetStatus
      })
      .then(res => {
        if (res && res.code === 200) {
          this.$message.success(actionText + '成功');
          
          // 更新本地状态
          lock.switchStatus = targetStatus;
          lock.status = targetStatus === 1 ? '已开锁' : '已关锁';
          lock.statusClass = targetStatus === 1 ? 'unlocked' : 'locked';
          lock.statusIcon = targetStatus === 1 ? 'fas fa-unlock' : 'fas fa-lock';
          
          // 更新统计数据
          this.updateStats();
        } else {
          this.$message.error(res.msg || actionText + '失败');
        }
      })
      .catch(error => {
        console.error(actionText + '失败:', error);
        this.$message.error(actionText + '失败: ' + error.message);
        
        // 处理401未授权错误
        if (error.message.includes('401')) {
          const Cookie = require('js-cookie');
          Cookie.remove('token');
          localStorage.removeItem('userInfo');
          this.$router.push('/login');
        }
      })
      .finally(() => {
        lock.operating = false;
      });
    },
    
    // 旧的开锁方法（保留兼容性）
    unlockDevice(lock) {
      // 重定向到新的切换方法
      this.toggleLockStatus(lock);
    },
    
    // 同步设备状态
    syncDeviceStatus() {
      if (!this.checkAuth()) return;
      
      this.syncing = true;
      this.$message.info('正在同步设备状态...');
      
      this.$get(SMARTLOCK_API.LOCK_QUERY_STATUS)
        .then(res => {
          if (res && res.code === 200) {
            this.$message.success('状态同步成功，正在重新加载表格...');
            // 重新加载表格内容
            this.loadLocks();
          } else {
            this.$message.error(res.msg || '状态同步失败');
          }
        })
        .catch(error => {
          console.error('状态同步失败:', error);
          this.$message.error('状态同步失败: ' + (error.message || '网络异常'));
          
          // 处理401未授权错误
          if (error.response && error.response.status === 401) {
            const Cookie = require('js-cookie');
            Cookie.remove('token');
            localStorage.removeItem('userInfo');
            this.$router.push('/login');
          }
        })
        .finally(() => {
          this.syncing = false;
        });
    },
    
    // 查看门锁详情
    viewLockDetails(lock) {
      if (!this.checkAuth()) return;
      
      this.detailsLock = { ...lock };
      this.showDetailsModal = true;
    },
    
    // 关闭详情模态框
    closeDetailsModal() {
      this.showDetailsModal = false;
      this.detailsLock = null;
      this.refreshingDetails = false;
    },
    
    // 刷新门锁详情（使用getById接口获取最新数据）
    refreshLockDetails() {
      if (!this.checkAuth() || !this.detailsLock) return;
      
      this.refreshingDetails = true;
      
      this.$get(SMARTLOCK_API.LOCK_GET_BY_ID, { lockId: this.detailsLock.lockId })
        .then(res => {
          if (res && res.code === 200 && res.data) {
            // 格式化最新的锁信息
            const updatedLock = this.formatLockInfo(res.data);
            this.detailsLock = { ...updatedLock };
            
            // 同时更新主列表中的对应项
            const index = this.locks.findIndex(lock => lock.lockId === updatedLock.lockId);
            if (index !== -1) {
              this.locks[index] = { ...this.locks[index], ...updatedLock };
              this.updateStats(); // 更新统计数据
            }
            
            this.$message.success('设备状态已刷新');
          } else {
            this.$message.error(res.msg || '获取设备详情失败');
          }
        })
        .catch(error => {
          console.error('刷新设备详情失败:', error);
          this.$message.error('刷新失败: ' + (error.message || '网络异常'));
          
        if (error.response && error.response.status === 401) {
          const Cookie = require('js-cookie');
          Cookie.remove('token');
          localStorage.removeItem('userInfo');
          this.$router.push('/login');
        }
        })
        .finally(() => {
          this.refreshingDetails = false;
        });
    },

    // 编辑门锁信息
    editLock(lock) {
      if (!this.checkAuth()) return;
      
      this.editingLock = { ...lock };
      this.showEditModal = true;
    },
     async changeCollege() {
      await this.$get("/api/smart/lock/getCollege").then((res) => {
        this.collegeList = res.data;
      });
    },

    // 新增框
    handleAddition(index,row){
      this.messageBox = true
      this.messageBoxTitle = '新增'
      this.changeCollege();
      this.newLockForm = {
        ipAddress: '',
        snCode: '',
        portNumber: null,
        switch_status: 0,
        college: '',
        classroom: '',
        remarks: ''
      }
    },
    cancelNewLock() {
      this.messageBox = false
    },
    saveNewLock() {
      if (!this.checkAuth()) return
      this.$refs.newLockFormRef.validate(valid => {
        if (!valid) return
        this.creating = true
        this.$post('/api/smart/lock/addLockInfo', this.newLockForm)
          .then(res => {
            if (res && res.code === 200) {
              this.$message.success('新增成功')
              this.messageBox = false
              this.loadLocks()
            } else {
              this.$message.error(res.msg || '新增失败')
            }
          })
          .catch(err => {
            this.$message.error('新增失败: ' + (err.message || '网络异常'))
          })
          .finally(() => {
            this.creating = false
          })
      })
    },
    
    // 关闭编辑模态框
    closeEditModal() {
      this.showEditModal = false;
      this.editingLock = {};
    },
    
    // 保存门锁信息
    saveLockInfo() {
      if (!this.checkAuth()) return;
      
      this.saving = true;
      
      this.$post(SMARTLOCK_API.LOCK_UPDATE, this.editingLock)
        .then(res => {
          if (res && res.code === 200) {
            // 更新本地数据 - 使用 Vue.set 确保响应式更新
            const index = this.locks.findIndex(lock => lock.lockId === this.editingLock.lockId);
            if (index !== -1) {
              // 保持操作状态和格式化信息，使用$set确保响应式更新
              const updatedLock = {
                ...this.locks[index],
                ...this.editingLock,
                name: this.editingLock.college && this.editingLock.classroom 
                  ? `${this.editingLock.college}-${this.editingLock.classroom}` 
                  : `设备${this.editingLock.lockId}`
              };
              
              // 使用Vue.set确保响应式更新
              this.$set(this.locks, index, updatedLock);
              
              // 强制更新组件以确保视图刷新
              this.$forceUpdate();
              
              console.log('本地数据已更新:', updatedLock);
            }
            
            this.$message.success('门锁信息保存成功');
            this.closeEditModal();
          } else {
            this.$message.error(res.msg || '保存失败');
          }
        })
        .catch(error => {
          console.error('保存门锁信息失败:', error);
          this.$message.error('保存失败: ' + error.message);
          
          // 处理401未授权错误
          if (error.message.includes('401')) {
            const Cookie = require('js-cookie');
            Cookie.remove('token');
            localStorage.removeItem('userInfo');
            this.$router.push('/login');
          }
        })
        .finally(() => {
          this.saving = false;
        });
    },
    
    // 刷新数据
    refreshData() {
      this.loadLocks();
    },
    
    // 切换自动刷新
    toggleAutoRefresh(enabled) {
      if (enabled) {
        this.startAutoRefresh();
        this.$message.success('已开启自动刷新，每30秒更新一次数据');
      } else {
        this.stopAutoRefresh();
        this.$message.info('已关闭自动刷新');
      }
    },
    
    // 开始自动刷新
    startAutoRefresh() {
      this.stopAutoRefresh(); // 先停止之前的定时器
      this.refreshTimer = setInterval(() => {
        if (!this.loading && !this.searching) {
          console.log('自动刷新设备数据...');
          this.loadLocks();
        }
      }, 30000); // 每30秒刷新一次
    },
    
    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    
    // ===== 每周定时开锁相关方法 =====
    
    // 设置每周定时开锁 (单个)
    setWeeklyTimer(lock) {
      this.isBatchTimerMode = false;
      this.selectedLockForTimer = lock;
      this.timerFormData.scheduleHour = 9;
      this.timerFormData.scheduleMinute = 0;
      this.timerFormData.scheduleDaysOfWeek = [];
      this.timerFormData.loopCount = 0;
      this.resetBatchProgress();
      this.showScheduleModal = true;
    },
    
    // 批量设置每周定时开锁
    batchSetWeeklyTimer() {
      if (this.selectedLocks.length === 0) {
        this.$message.warning('请先选择要设置定时开锁的设备');
        return;
      }
      
      this.isBatchTimerMode = true;
      this.selectedLockForTimer = null;
      this.timerFormData.scheduleHour = 9;
      this.timerFormData.scheduleMinute = 0;
      this.timerFormData.scheduleDaysOfWeek = [];
      this.timerFormData.loopCount = 0;
      this.resetBatchProgress();
      this.batchTimerProgress.total = this.selectedLocks.length;
      this.showScheduleModal = true;
    },
    
    // 验证时间
    validateTime(rule, value, callback) {
      const hour = this.timerFormData.scheduleHour;
      const minute = this.timerFormData.scheduleMinute;
      
      if (typeof hour !== 'number' || hour < 0 || hour > 23) {
        return callback(new Error('请选择有效的小时 (0-23)'));
      }
      if (typeof minute !== 'number' || minute < 0 || minute > 59) {
        return callback(new Error('请选择有效的分钟 (0-59)'));
      }
      callback();
    },
    
    // 验证选择的星期
    validateDaysOfWeek(rule, value, callback) {
      const days = this.timerFormData.scheduleDaysOfWeek;
      
      if (!Array.isArray(days) || days.length === 0) {
        return callback(new Error('请至少选择一天'));
      }
      
      // 验证每个选择的日期是否有效 (0-6)
      const invalidDays = days.filter(day => typeof day !== 'number' || day < 0 || day > 6);
      if (invalidDays.length > 0) {
        return callback(new Error('选择的日期无效'));
      }
      
      callback();
    },
    
    // 验证循环次数
    validateLoopCount(rule, value, callback) {
      const loopCount = this.timerFormData.loopCount;
      
      if (typeof loopCount !== 'number') {
        return callback(new Error('请输入有效的循环次数'));
      }
      
      if (loopCount < 0 || loopCount > 99999) {
        return callback(new Error('循环次数必须在0-99999之间'));
      }
      
      callback();
    },
    
    // 重置批量进度
    resetBatchProgress() {
      this.batchTimerProgress = {
        current: 0,
        total: 0,
        success: 0,
        failed: 0
      };
    },
    
    // 根据锁ID获取锁名称
    getLockNameById(lockId) {
      const lock = this.locks.find(l => l.lockId === lockId);
      return lock ? lock.name : `设备${lockId}`;
    },
    
    // 选择工作日
    selectWorkdays() {
      this.timerFormData.scheduleDaysOfWeek = [0, 1, 2, 3, 4];
    },
    
    // 选择周末
    selectWeekends() {
      this.timerFormData.scheduleDaysOfWeek = [5, 6];
    },
    
    // 选择每天
    selectAllDays() {
      this.timerFormData.scheduleDaysOfWeek = [0, 1, 2, 3, 4, 5, 6];
    },
    
    // 清除选择
    clearDays() {
      this.timerFormData.scheduleDaysOfWeek = [];
    },
    
    // 创建每周定时器
    createWeeklyTimer() {
      console.log('开始创建定时器，表单数据:', this.timerFormData);
      
      this.$refs.scheduleForm.validate((valid) => {
        console.log('表单验证结果:', valid);
        
        if (valid) {
          const daysText = this.timerFormData.scheduleDaysOfWeek.map(day => {
            const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            return dayNames[day];
          }).join('、');
          
          const timeText = `${this.timerFormData.scheduleHour}:${String(this.timerFormData.scheduleMinute).padStart(2, '0')}`;
          
          let confirmMessage;
          if (this.isBatchTimerMode) {
            confirmMessage = `确定要为选中的 ${this.selectedLocks.length} 个设备设置每周定时开锁吗？\n时间：${timeText}\n重复：${daysText}`;
          } else {
            confirmMessage = `确定要为设备"${this.selectedLockForTimer.name}"设置每周定时开锁吗？\n时间：${timeText}\n重复：${daysText}`;
          }
          
          this.$confirm(
            confirmMessage,
            '每周定时器确认', 
            {
              confirmButtonText: '确定设置',
              cancelButtonText: '取消',
              type: 'warning',
              center: true
            }
          ).then(() => {
            if (this.isBatchTimerMode) {
              this.executeBatchCreateWeeklyTimer();
            } else {
              this.executeCreateWeeklyTimer();
            }
          }).catch(() => {
            this.$message.info('已取消定时设置');
          });
        } else {
          this.$message.warning('请完善定时设置信息');
          console.error('表单验证失败');
          return false;
        }
      });
    },
    
    // 执行创建每周定时器 (单个)
    executeCreateWeeklyTimer() {
      this.scheduleSaving = true;
      
      // 准备请求数据 - 严格按照 ScheduleTaskDto 格式
      const timerData = {
        taskId: 0,                                          // int - 新建任务时为0
        lockId: this.selectedLockForTimer.lockId,           // int
        userId: 0,                                          // int - 后端会自动设置
        timedOperation: 1,                                  // int - 1表示开锁操作
        taskDetails: `每周定时开锁任务 - ${this.selectedLockForTimer.name}`, // String
        taskStatus: 1,                                      // int - 1表示启用
        isLoop: 1,                                          // int - 1表示循环执行
        remarks: `为设备"${this.selectedLockForTimer.name}"设置的每周定时开锁`, // String
        hour: this.timerFormData.scheduleHour,              // int
        minute: this.timerFormData.scheduleMinute,          // int
        countDay: this.timerFormData.scheduleDaysOfWeek,    // int[] - 每周的天数
        loopCount: this.timerFormData.loopCount             // int - 循环次数
      };
      
      console.log('创建每周定时器:', timerData);
      
      this.$post(SMARTLOCK_API.ADD_TIMER, timerData)
        .then(res => {
          if (res && res.code === 200) {
            this.$message.success('每周定时开锁设置成功！');
            this.showScheduleModal = false;
            this.resetWeeklyTimerForm();
          } else {
            this.$message.error(res.msg || '定时设置失败');
          }
        })
        .catch(error => {
          console.error('设置每周定时器失败:', error);
          this.$message.error('定时设置失败: ' + (error.message || '网络异常'));
        })
        .finally(() => {
          this.scheduleSaving = false;
        });
    },
    
    // 执行批量创建每周定时器
    executeBatchCreateWeeklyTimer() {
      this.scheduleSaving = true;
      this.resetBatchProgress();
      this.batchTimerProgress.total = this.selectedLocks.length;
      
      let completedCount = 0;
      const totalCount = this.selectedLocks.length;
      
      this.$message.info(`开始批量设置定时任务，共 ${totalCount} 个设备...`);
      
      // 为每个选中的锁创建定时任务
      this.selectedLocks.forEach((lockId, index) => {
        const timerData = {
          taskId: 0,                                          // int - 新建任务时为0
          lockId: parseInt(lockId),                           // int
          userId: 0,                                          // int - 后端会自动设置
          timedOperation: 1,                                  // int - 1表示开锁操作
          taskDetails: `批量每周定时开锁任务 - 设备${lockId}`,    // String
          taskStatus: 1,                                      // int - 1表示启用
          isLoop: 1,                                          // int - 1表示循环执行
          remarks: `批量设置的每周定时开锁任务 - 设备${lockId}`, // String
          hour: this.timerFormData.scheduleHour,              // int
          minute: this.timerFormData.scheduleMinute,          // int
          countDay: this.timerFormData.scheduleDaysOfWeek,    // int[] - 每周的天数
          loopCount: this.timerFormData.loopCount             // int - 循环次数
        };
        
        // 延迟执行，避免并发过多
        setTimeout(() => {
          this.$post(SMARTLOCK_API.ADD_TIMER, timerData)
            .then(res => {
              if (res && res.code === 200) {
                this.batchTimerProgress.success++;
                console.log(`设备 ${lockId} 定时任务设置成功`);
              } else {
                this.batchTimerProgress.failed++;
                console.error(`设备 ${lockId} 定时任务设置失败:`, res.msg);
              }
            })
            .catch(error => {
              this.batchTimerProgress.failed++;
              console.error(`设备 ${lockId} 定时任务设置失败:`, error);
            })
            .finally(() => {
              completedCount++;
              this.batchTimerProgress.current = completedCount;
              
              // 所有任务完成
              if (completedCount === totalCount) {
                this.scheduleSaving = false;
                const successCount = this.batchTimerProgress.success;
                const failedCount = this.batchTimerProgress.failed;
                
                if (successCount === totalCount) {
                  this.$message.success(`批量定时设置完成！全部 ${totalCount} 个设备设置成功`);
                } else if (successCount > 0) {
                  this.$message.warning(`批量定时设置完成！成功 ${successCount} 个，失败 ${failedCount} 个`);
                } else {
                  this.$message.error('批量定时设置失败，请检查网络连接或设备状态');
                }
                
                // 2秒后关闭窗口
                setTimeout(() => {
                  this.showScheduleModal = false;
                  this.resetWeeklyTimerForm();
                }, 2000);
              }
            });
        }, index * 200); // 每200ms执行一个，避免服务器压力过大
      });
    },
    
    // 取消每周定时器设置
    cancelWeeklyTimer() {
      this.showScheduleModal = false;
      this.resetWeeklyTimerForm();
      this.$message.info('已取消定时设置');
    },
    
    // 重置表单
    resetWeeklyTimerForm() {
      this.selectedLockForTimer = null;
      this.isBatchTimerMode = false;
      this.timerFormData.scheduleHour = 9;
      this.timerFormData.scheduleMinute = 0;
      this.timerFormData.scheduleDaysOfWeek = [];
      this.timerFormData.loopCount = 0;
      this.resetBatchProgress();
      this.$refs.scheduleForm && this.$refs.scheduleForm.clearValidate();
    },
    
    
    
    
  },
  
  // 组件销毁时清理定时器
  beforeDestroy() {
    this.stopAutoRefresh();
  }
}
</script>

<style scoped>
.smartlock-page-container {
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  position: relative;
  /* 确保滚动平滑 */
  scroll-behavior: smooth;
  /* 防止内容溢出到父容器 */
  contain: layout style paint;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-left h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.header-right {
  display: flex;
  align-items: center;
}

.lock-details-content {
  max-height: 500px;
  overflow-y: auto;
}

.details-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.details-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px 20px;
  padding: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.detail-item-full {
  grid-column: 1 / -1;
}

.detail-label {
  font-weight: 600;
  color: #333;
  min-width: 80px;
  margin-right: 8px;
  font-size: 14px;
}

.detail-value {
  color: #666;
  font-size: 14px;
  word-break: break-all;
}

.detail-value .el-tag {
  margin: 0;
}

/* 统计概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.stat-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.2rem;
}

.stat-icon.unlocked {
  background: linear-gradient(135deg, #2ed573, #17c0eb);
}

.stat-icon.locked {
  background: linear-gradient(135deg, #ff4757, #c44569);
}

.stat-title {
  font-weight: 600;
  color: #333;
}

.stat-content {
  text-align: center;
  padding: 1rem 0;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.stat-desc {
  font-size: 0.9rem;
  color: #666;
  margin: 0;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.selected-count {
  color: #92400e;
  font-weight: 600;
  font-size: 14px;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table .cell {
  padding: 0 8px;
}

.el-table th {
  background-color: #fafafa;
}

.el-table--border td, .el-table--border th {
  border-right: 1px solid #ebeef5;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 6px;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  margin: 0;
  padding: 6px 10px;
  font-size: 12px;
  white-space: nowrap;
  min-width: 60px;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
}

/* 表单项间距 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 按钮组样式 */
.el-form-item:last-child {
  margin-right: 0;
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 8px;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.error-icon {
  font-size: 3rem;
  color: #ff4757;
  margin-bottom: 1rem;
}

.error-state h3 {
  color: #333;
  margin-bottom: 0.5rem;
}

.error-state p {
  color: #666;
  margin-bottom: 2rem;
}

.empty-state {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 2rem;
}


.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 15px 0;
}

/* 定时开锁模态框样式 */
.schedule-content {
  padding: 10px 0;
}

.schedule-content .el-form-item {
  margin-bottom: 20px;
}

.schedule-content .el-alert {
  margin-bottom: 20px;
}

/* 定时任务列表样式 */
.schedule-list-content {
  padding: 0;
}

.schedule-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.schedule-list-content .el-table {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.schedule-list-content .el-table th {
  background: #f8f9fa;
  color: #333;
  font-weight: 600;
}

.schedule-list-content .el-table td {
  padding: 12px 0;
}

.schedule-list-content .el-tag {
  border-radius: 4px;
  font-size: 12px;
}

.schedule-list-content .el-button--mini {
  padding: 5px 8px;
  font-size: 12px;
}

/* 模态框样式修复 */
.smart-lock-modal {
  z-index: 3000 !important;
}

.smart-lock-modal .el-dialog {
  margin-top: 5vh !important;
  margin-bottom: 5vh !important;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.smart-lock-modal .el-dialog__header {
  background: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 15px 20px;
}

.smart-lock-modal .el-dialog__title {
  font-weight: 600;
  color: #333;
}

.smart-lock-modal .el-dialog__body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.smart-lock-modal .el-dialog__footer {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px 20px 20px;
  background: #f8f9fa;
}

/* 移除遮罩层样式（已设置 :modal="false"） */

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .el-table {
    font-size: 13px;
  }
  
  .el-table .cell {
    padding: 0 6px;
  }
}

@media screen and (max-width: 768px) {
  .smartlock-page-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
    text-align: center;
  }
  
  .header-left h2 {
    border-bottom: none;
    padding-bottom: 0;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-form {
    padding: 15px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
    margin-right: 0;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  /* 移动端操作按钮样式 */
  .action-buttons {
    gap: 2px;
  }
  
  .action-buttons .el-button {
    padding: 4px 6px;
    font-size: 11px;
  }
  
  .pagination-wrapper {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
}


/* 自定义滚动条样式 */
.smartlock-page-container::-webkit-scrollbar {
  width: 8px;
}

.smartlock-page-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
  margin: 4px;
}

.smartlock-page-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.smartlock-page-container::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.smartlock-page-container::-webkit-scrollbar-corner {
  background: transparent;
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* ===== 每周定时开锁模态框样式 ===== */
.weekly-timer-modal .el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.weekly-timer-modal .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 24px;
  text-align: center;
}

.weekly-timer-modal .el-dialog__title {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.weekly-timer-modal .el-dialog__body {
  padding: 24px;
  max-height: 600px;
  overflow-y: auto;
}

/* 设备信息区域 */
.device-info-section {
  margin-bottom: 20px;
}

.batch-device-preview {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  margin-top: 15px;
}

.device-list-header {
  margin-bottom: 10px;
}

.device-count {
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

.device-list-content {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-height: 100px;
  overflow-y: auto;
}

.more-devices {
  color: #6c757d;
  font-style: italic;
  font-size: 12px;
  padding: 4px 8px;
  background: #e9ecef;
  border-radius: 12px;
  line-height: 20px;
}

.single-device-info {
  background: #e8f4fd;
  border: 1px solid #b3d7ff;
  border-radius: 6px;
  padding: 12px 16px;
  margin-top: 15px;
}

.device-name {
  color: #0366d6;
  font-weight: 600;
}

/* 批量进度区域 */
.batch-progress-section {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 16px;
  margin: 15px 0;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  color: #856404;
  font-weight: 600;
}

.progress-text {
  font-size: 14px;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  margin-top: 8px;
}

.success-count {
  color: #155724;
  font-weight: 500;
}

.failed-count {
  color: #721c24;
  font-weight: 500;
}

/* 定时表单区域 */
.timer-form-section {
  background: #fff;
  border-radius: 8px;
}

.time-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.time-separator {
  font-weight: 600;
  color: #495057;
  font-size: 16px;
  margin: 0 4px;
}

.days-selection-container {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
}

.days-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: space-between;
}

.day-checkbox {
  flex: 1;
  min-width: 60px;
  text-align: center;
}

.day-checkbox .el-checkbox__label {
  font-size: 14px;
  font-weight: 500;
  padding-left: 8px;
}

.quick-select-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
  padding-top: 8px;
}

.quick-select-buttons .el-button {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 16px;
  border: 1px solid #ddd;
  background: #f8f9fa;
  color: #495057;
}

.quick-select-buttons .el-button:hover {
  color: #007bff;
  border-color: #007bff;
  background: #e3f2fd;
}

/* 循环次数输入样式 */
.loop-count-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loop-count-unit {
  font-size: 14px;
  color: #495057;
  font-weight: 500;
}

.loop-count-help {
  font-size: 12px;
  color: #6c757d;
  font-style: italic;
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .weekly-timer-modal .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .time-input-group {
    justify-content: center;
  }
  
  .days-checkbox-group {
    flex-direction: column;
    gap: 12px;
  }
  
  .day-checkbox {
    min-width: auto;
    text-align: left;
  }
  
  .quick-select-buttons {
    flex-direction: column;
    gap: 6px;
  }
  
  .device-list-content {
    max-height: 80px;
  }
  
  .batch-device-preview {
    padding: 12px;
  }
  
  .weekly-timer-modal .el-dialog__body {
    padding: 16px;
    max-height: 500px;
  }
}

/* 进度条样式优化 */
.weekly-timer-modal .el-progress-bar__outer {
  border-radius: 8px;
  background: #e9ecef;
}

.weekly-timer-modal .el-progress-bar__inner {
  border-radius: 8px;
  background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
}

/* 标签样式优化 */
.device-list-content .el-tag {
  margin: 2px 4px;
  border-radius: 12px;
  font-size: 12px;
  padding: 2px 8px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 表单验证错误样式 */
.weekly-timer-modal .el-form-item.is-error .el-form-item__label {
  color: #f56565;
}

.weekly-timer-modal .el-form-item.is-error .el-input__inner {
  border-color: #f56565;
}

/* 按钮组样式 */
.weekly-timer-modal .dialog-footer {
  padding: 16px 24px;
  text-align: center;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
}

.weekly-timer-modal .dialog-footer .el-button {
  margin: 0 8px;
  min-width: 100px;
}

/* 滚动条优化 */
.weekly-timer-modal .el-dialog__body::-webkit-scrollbar {
  width: 6px;
}

.weekly-timer-modal .el-dialog__body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.weekly-timer-modal .el-dialog__body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
</style>
